from time import sleep
import allure
from selenium.webdriver.common.by import By
from data.names import PublicSel, SpSel
from common.commin.commin import object_left_click, object_send_keys, elements_clickable, elements_visibility, \
    allure_save_screenshot
from common.log.log import log
from data.randomly_generated_data import *
from po.jinhua.ht.api.ht_api import api_search_store_product_type
from po.jinhua.ht.jinhua_ht_main.jinhua_base import JHBase
from po.jinhua.ht.jinhua_ht_main.jinhua_ht_main_page import JHHTHomePage


# 商品管理-菜单页页
class CommodityManagementPage(JHBase):
    """
    商品管理-菜单页页
    """

    @allure.step('获取tips提示文案')
    def get_tips(self):
        try:

            elements_visibility(self.driver, By.XPATH, "//div[@role='alert']")
            tips = self.driver.find_element(By.XPATH, "//div[@role='alert']").text
            # allure_save_screenshot(self.driver, '获取tips的界面截图')
            log.info(f'获取tips提示文案为：{tips}')
            sleep(2)  # 等待系统处理结束
            return tips
        except Exception as e:
            log.error(f'获取tips提示文案出现错误，异常为{e}')
            raise e

    @allure.step('商品管理-打开仓库中的商品')
    def open_goods_in_warehouse(self):
        """
        商品管理-打开仓库中的商品
        """
        try:
            log.info('商品管理-打开仓库中的商品')
            object_left_click(self.driver, (By.XPATH, "//div[contains(text(),'仓库中商品')]"))
            elements_clickable(self.driver, By.CSS_SELECTOR, '.demo-image__preview')  # 列表加载完可点击（商品图片）才可进行后续操作
            return CommodityManagementPage(self.driver)
        except Exception as e:
            log.error(f'打开仓库中的商品出现错误，异常为{e}')
            raise e

    @allure.step('商品管理-打开商品回收站')
    def open_recycling_station(self):
        """
        商品管理-打开商品回收站
        """
        try:
            log.info('商品管理-打开商品回收站')
            object_left_click(self.driver, (By.XPATH, "//div[contains(text(),'商品回收站')]"))
            elements_clickable(self.driver, By.CSS_SELECTOR, '.demo-image__preview')  # 列表加载完可点击（商品图片）才可进行后续操作
            return CommodityManagementPage(self.driver)
        except Exception as e:
            log.error(f'商品管理-打开商品回收站出现错误，异常为{e}')
            raise e

    @allure.step('商品管理-加入回收站')
    def add_item_delete(self, name):
        """
        商品管理-加入回收站
        name: 待加入回收站的商品名称
        """
        try:
            log.info('商品管理：开始加入回收站')
            # elements_clickable(self.driver, By.XPATH, "//*[text()='加入回收站']")
            elements_clickable(self.driver, By.CSS_SELECTOR, '.demo-image__preview')  # 列表加载完可点击（商品图片）才可进行后续操作
            sel = self.driver.find_elements(By.XPATH, f"//*[text()='{name}']/../..//button")  # 点击商品名称右侧的“加入回收站”
            sel[-2].click()
            sleep(1)
            object_left_click(self.driver, (By.XPATH, "//span[contains(text(),'确定')]"))
            log.info('开始检查是否移动到回收站成功.....')

            tps = self.get_tips()
            sleep(3)  # 等待系统操作完成
            if tps == '删除成功':
                response_text = api_search_store_product_type(self.driver, name, 2)
                # log.info(f'哈哈，我是调试{response_text}')
                if name not in response_text:
                    log.info('商品加入回收站成功！')
                    return CommodityManagementPage(self.driver), True

            # self.search_item(name)
            # check_text = self.driver.find_element(By.XPATH, "//*[@class='el-pagination__total']").text
            # log.info(f'调试日志：{check_text}')
            # if check_text == '共 0 条':
            #     log.info(f'商品加入到回收站成功！商品名称为：{name}')
            #     return CommodityManagementPage(self.driver), True
            # else:
            #     sel = self.driver.find_elements(By.XPATH, f"//*[text()='{name}']/../..//button")  # 点击商品名称右侧的“加入回收站”
            #     sel[-1].click()
            #     sleep(1)
            #     object_left_click(self.driver, (By.XPATH, "//span[contains(text(),'确定')]"))
            #     sleep(3)  # 等待系统操作
            #
            #     log.info('【再次】检查是否移动到回收站成功.....')
            #     self.search_item(name)
            #     check_text = self.driver.find_element(By.XPATH, "//*[@class='el-pagination__total']").text
            #     log.info(f'调试日志：{check_text}')
            #     if check_text == '共 0 条':
            #         log.info(f'商品加入到回收站成功！商品名称为：{name}')
            #         return CommodityManagementPage(self.driver), True
        except Exception as e:
            log.error(f'商品管理：加入回收站站出现错误，异常为{e}')
            raise e

    @allure.step('商品管理-删除商品')
    def item_delete(self, name):
        """
        商品管理-商品回收站：删除
        name: 待加入回收站的商品名称
        """
        try:
            log.info('商品管理-商品回收站：开始删除商品')
            sel = self.driver.find_elements(By.XPATH, f"//*[text()='{name}']/../..//button")
            sel[-2].click()
            sleep(1)
            object_left_click(self.driver, (By.XPATH, "//span[contains(text(),'确定')]"))
            log.info('开始检查是否删除成功.....')
            tps = self.get_tips()
            sleep(3)  # 等待系统操作完成
            if tps == '删除成功':
                for i in range(3):
                    response_text = api_search_store_product_type(self.driver, name, 5)
                    # log.info(f'哈哈，我是调试{response_text}')
                    if name not in response_text:
                        log.info('API接口校验：商品删除成功！')
                        return CommodityManagementPage(self.driver), True
        except Exception as e:
            self.open_recycling_station().item_delete(name)
            log.error(f'商品管理-商品回收站：删除商品 {name} 出现错误，异常为{e}')
            raise e

    @allure.step('商品管理：输入商品信息，进行搜索商品')
    def search_item(self, tab, key):
        """
        商品管理：输入商品信息，进行搜索商品
        el_input_goods 商品名称输入框
        el_icon_search 搜索按钮
        """
        try:
            log.info('商品管理：输入商品信息，进行搜索商品')
            if tab == '出售中商品':
                object_left_click(self.driver, SpSel.el_sp_tab_1())
            elif tab == '仓库中商品':
                object_left_click(self.driver, SpSel.el_sp_tab_2())
            elif tab == '已经售馨商品':
                object_left_click(self.driver, SpSel.el_sp_tab_3())
            elif tab == '警戒库存':
                object_left_click(self.driver, SpSel.el_sp_tab_4())
            elif tab == '商品回收站':
                object_left_click(self.driver, SpSel.el_sp_tab_5())
            object_send_keys(self.driver, SpSel.el_input_goods(), key)
            object_left_click(self.driver, PublicSel.el_icon_search())
            elements_visibility(self.driver, By.CSS_SELECTOR, '.el-card__body')  # 检查列表可见，才可进行后续操作
            sleep(2)
            return CommodityManagementPage(self.driver)
        except Exception as e:
            log.error(f'搜索商品出现错误，异常为{e}')
            raise e

    @allure.step('商品管理：添加商品')
    def add_item(self, name):
        """
        添加商品
        """
        try:
            object_left_click(self.driver, SpSel.el_add_product_button())  # 点击添加商品按钮
            sleep(1)

            """#####################   操作  #####################"""
            log.info('开始操作添加商品，步骤有点多，请稍后......')
            """配置商品信息"""
            object_send_keys(self.driver, SpSel.el_trade_name(), name)  # 输入商品名称
            object_left_click(self.driver, SpSel.el_category())  # 点击商品分类的“请输入”
            object_left_click(self.driver, SpSel.el_category_box())  # 选中”健康产品“

            if 'yc' in self.driver.current_url:
                object_left_click(self.driver, SpSel.el_sp_etem_1())  # 点击一下，目的是收缩上一个的下拉框
                object_send_keys(self.driver, SpSel.el_sp_etem_1(), generate_random_code())  # 输入商品编号
            elif 'yg' in self.driver.current_url:
                object_left_click(self.driver, SpSel.el_sp_etem())  # 点击一下，目的是收缩上一个的下拉框
                object_send_keys(self.driver, SpSel.el_sp_etem(), generate_random_code())  # 输入商品编号

            object_send_keys(self.driver, SpSel.el_sp_product_keywords(), name)  # 输入商品关键字
            object_send_keys(self.driver, SpSel.el_sp_product_unit(), generate_random_unit())  # 输入单位
            object_send_keys(self.driver, SpSel.el_sp_product_description(), generate_random_intro())  # 输入商品简介
            object_left_click(self.driver, SpSel.el_sp_tax_code())  # 点击税收编码，弹出显示下拉框
            object_left_click(self.driver, SpSel.el_sp_tax_code_bj())  # 点击”白酒“
            object_left_click(self.driver, SpSel.el_sp_cover_image())  # 点击上传商品封面图
            object_left_click(self.driver, SpSel.el_sp_pic())  # 选中其中一个图片
            object_left_click(self.driver, SpSel.el_sp_using_pictures())  # 点击按钮“使用选中图片”
            object_left_click(self.driver, SpSel.el_sp_rotation_image())  # 点击上传商品轮播图
            object_left_click(self.driver, SpSel.el_sp_pic())  # 选中其中一个图片
            object_left_click(self.driver, SpSel.el_sp_using_pictures())  # 点击按钮“使用选中图片”
            object_left_click(self.driver, SpSel.el_freight_template())  # 点击运费模板“请选择”
            object_left_click(self.driver, SpSel.el_sp_default_shipping_cost())  # 点击默认运费
            object_left_click(self.driver, SpSel.el_select_spec())  # 点击默规格选择“请选择”
            object_left_click(self.driver, SpSel.el_sp_500ml())  # 选择规格：500ml
            object_left_click(self.driver, PublicSel.el_confirm_button())  # 点击确认按钮
            """配置商品属性"""
            self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")  # 滑动到底部
            object_left_click(self.driver, SpSel.el_sp_attributes_upload_image())  # 商品属性点击上传图按钮
            object_left_click(self.driver, SpSel.el_sp_pic())  # 选中其中一个图片
            object_left_click(self.driver, SpSel.el_sp_using_pictures())  # 点击按钮“使用选中图片”
            attribute = self.driver.find_elements(By.XPATH, SpSel.el_sp_attributes_input())  # 商品属性
            attribute[0].send_keys(generate_random_number())  # 售价
            attribute[1].send_keys(generate_random_number())  # 成本价
            attribute[2].send_keys(generate_random_number())  # 原价
            attribute[3].send_keys(generate_random_number(1000000))  # 库存
            attribute[4].send_keys(generate_random_code())  # 商品规格编号
            attribute[5].send_keys(generate_random_number())  # 重量（kg）
            attribute[6].send_keys(generate_random_number())  # 体积(m³)
            object_left_click(self.driver, SpSel.el_sp_next_step())  # 下一步
            object_left_click(self.driver, SpSel.el_sp_next_step())  # 下一步

            """其他设置页面"""
            # object_left_click(self.driver, SpSel.el_sp_new_product_introduction())  # 选择新品上新
            object_left_click(self.driver, PublicSel.el_submit_button())  # 点击提交
            log.info('添加商品完成！')
            return CommodityManagementPage(self.driver)
        except Exception as e:
            log.error(f'添加商品出现错误，异常为{e}')
            raise e

    @allure.step('积分商品管理：添加积分商品')
    def add_item_integral(self, name, mode=0):
        """
        添加积分商品
        """
        try:
            if mode == 0:  # 新增积分商品
                object_left_click(self.driver, SpSel.el_add_product_button())  # 点击添加商品按钮
                object_left_click(self.driver, SpSel.el_add_integral_sp_button())  # 点击新增积分商品按钮
                sleep(1)

                """#####################   操作  #####################"""
                log.info('开始操作添加商品，步骤有点多，请稍后......')
                """配置商品信息"""
                object_send_keys(self.driver, SpSel.el_trade_name(), name)  # 输入商品名称
                object_left_click(self.driver, SpSel.el_category())  # 点击商品分类的“请输入”
                object_left_click(self.driver, SpSel.el_category_box())  # 选中”健康产品“
                object_left_click(self.driver, SpSel.el_sp_etem())  # 点击一下，目的是收缩上一个的下拉框
                object_send_keys(self.driver, SpSel.el_sp_etem(), generate_random_code())  # 输入商品编号
                object_send_keys(self.driver, SpSel.el_sp_product_keywords(), name)  # 输入商品关键字
                object_send_keys(self.driver, SpSel.el_sp_product_unit(), generate_random_unit())  # 输入单位
                object_send_keys(self.driver, SpSel.el_sp_product_description(), generate_random_intro())  # 输入商品简介
                object_left_click(self.driver, SpSel.el_sp_cover_image())  # 点击上传商品封面图
                object_left_click(self.driver, SpSel.el_sp_pic())  # 选中其中一个图片
                object_left_click(self.driver, SpSel.el_sp_using_pictures())  # 点击按钮“使用选中图片”
                object_left_click(self.driver, SpSel.el_sp_rotation_image())  # 点击上传商品轮播图
                object_left_click(self.driver, SpSel.el_sp_pic())  # 选中其中一个图片
                object_left_click(self.driver, SpSel.el_sp_using_pictures())  # 点击按钮“使用选中图片”
                object_left_click(self.driver, SpSel.el_freight_template())  # 点击运费模板“请选择”
                object_left_click(self.driver, SpSel.el_sp_default_shipping_cost())  # 点击默认运费
                object_left_click(self.driver, SpSel.el_select_spec())  # 点击默规格选择“请选择”
                object_left_click(self.driver, SpSel.el_sp_500ml())  # 选择规格：500ml
                object_left_click(self.driver, PublicSel.el_confirm_button())  # 点击确认按钮
                """配置商品属性"""
                self.driver.execute_script("window.scrollTo(0,document.body.scrollHeight);")  # 滑动到底部
                object_left_click(self.driver, SpSel.el_sp_attributes_upload_image())  # 商品属性点击上传图按钮
                object_left_click(self.driver, SpSel.el_sp_pic())  # 选中其中一个图片
                object_left_click(self.driver, SpSel.el_sp_using_pictures())  # 点击按钮“使用选中图片”
                attribute = self.driver.find_elements(By.XPATH, SpSel.el_sp_attributes_input())  # 商品属性
                attribute[0].send_keys(generate_random_number())  # 售价
                attribute[1].send_keys(generate_random_number())  # 成本价
                attribute[2].send_keys(generate_random_number())  # 原价
                attribute[3].send_keys(generate_random_number(1000000))  # 库存
                attribute[4].send_keys(generate_random_code())  # 商品规格编号
                attribute[5].send_keys(generate_random_number())  # 重量（kg）
                attribute[6].send_keys(generate_random_number())  # 体积(m³)
                object_left_click(self.driver, SpSel.el_sp_next_step())  # 下一步
                object_left_click(self.driver, SpSel.el_sp_next_step())  # 下一步

                """其他设置页面"""
                object_left_click(self.driver, PublicSel.el_submit_button())  # 点击提交
                log.info('添加积分商品完成！')
                return CommodityManagementPage(self.driver)
            elif mode == 1:
                # 从现有商品导入
                pass
        except Exception as e:
            log.error(f'添加商品出现错误，异常为{e}')
            raise e

    @allure.step('新增商品分类')
    def add_category(self, name):
        """
        新增商品分类
        """
        try:
            log.info('新增商品分类')
            JHHTHomePage(self.driver).open_menu('yg', '商品分类')
            object_left_click(self.driver, SpSel.el_fl_01())
            object_send_keys(self.driver, SpSel.el_fl_02(), name)
            object_left_click(self.driver, SpSel.el_fl_03())
        except Exception as e:
            log.error(f'搜索商品出现错误，异常为{e}')
            raise e

    @allure.step('删除商品分类')
    def del_category(self, name):
        """
        删除商品分类
        """
        try:
            log.info('删除商品分类')
            JHHTHomePage(self.driver).open_menu('yg', '商品分类')
            object_send_keys(self.driver, SpSel.el_fl_04(), name)
            object_left_click(self.driver, SpSel.el_fl_05())
            sleep(1)
            object_left_click(self.driver, SpSel.el_fl_06())
            object_left_click(self.driver, PublicSel.el_ok_button())  # 二次确认
        except Exception as e:
            log.error(f'删除商品分类，异常为{e}')
            raise e

    @allure.step('新增税收编码')
    def add_tax_code(self, name, number):
        """
        新增税收编码
        """
        try:
            log.info('新增税收编码')
            JHHTHomePage(self.driver).open_menu('yg', '税收编码')
            object_left_click(self.driver, SpSel.el_shui_01())
            object_send_keys(self.driver, SpSel.el_shui_02(), name)
            object_send_keys(self.driver, SpSel.el_shui_03(), number)
            object_left_click(self.driver, SpSel.el_shui_04())
        except Exception as e:
            log.error(f'搜索商品出现错误，异常为{e}')
            raise e

    @allure.step('删除税收编码')
    def del_tax_code(self, name):
        """
        删除税收编码
        """
        try:
            log.info('删除税收编码')
            JHHTHomePage(self.driver).open_menu('yg', '税收编码')
            object_send_keys(self.driver, SpSel.el_shui_05(), name)
            object_left_click(self.driver, SpSel.el_shui_06())
            object_left_click(self.driver, SpSel.el_shui_07())
            object_left_click(self.driver, SpSel.el_shui_08())
        except Exception as e:
            log.error(f'搜索商品出现错误，异常为{e}')
            raise e